import _ from 'lodash';

let filterFuns = {};
let parse = (item, ctx, eventCbk) => {
  if (_.isBoolean(item)) {
    return item;
  }
  if (_.isFunction(item)) {
    return item(ctx);
  }
  if (_.isString(item) && filterFuns[item]) {
    return filterFuns[item](ctx);
  }
  if (_.isObject(item) && filterFuns[item.name]) {
    return filterFuns[item.name](ctx, item, eventCbk);
  }
  if (_.isArray(item)) {
    return item.map((v) => {
      return parse(v, ctx, eventCbk);
    });
  }
  return false;
};

class Filter {
  funs = filterFuns;
  add(name, fun) {
    filterFuns[name] = fun;
  }
  //同步方式处理
  parse(conf, ctx, eventCbk) {
    if (!conf) {
      return false;
    }
    return parse(conf, ctx, eventCbk);
  }

  //按顺序处理，当遇到false或特定结果则停止,相当于管道，这种可以节省资源
}

let filter = new Filter();

export default filter;

filter.add('status', (ctx = {}, conf) => {
  const { record = {}, status } = ctx;
  const { data = [], dataIndex = 'status' } = conf;
  return data.indexOf(_.get(record, dataIndex) || status) >= 0;
});

filter.add('and', (ctx = {}, conf, eventCbk) => {
  let { data } = conf;
  if (!_.isArray(data)) {
    data = [data];
  }

  for (let i = 0; i < data.length; i++) {
    if (!filter.parse(data[i], ctx, eventCbk)) {
      return false;
    }
  }
  return true;
});

filter.add('or', (ctx = {}, conf, eventCbk) => {
  let { data } = conf;
  if (!_.isArray(data)) {
    data = [data];
  }

  for (let i = 0; i < data.length; i++) {
    if (filter.parse(data[i], ctx, eventCbk)) {
      return true;
    }
  }
  return false;
});